package com.shycloud.mido.homework.controller;

import com.shycloud.mido.homework.api.vo.MidoHomeworkComplateVO;
import com.shycloud.mido.homework.api.vo.MidoHomeworkMainVOMini;
import com.shycloud.mido.member.api.feign.RemoteMemberService;
import com.shycloud.mido.member.api.vo.MyTeacherVO;
import com.shycloud.mido.music.domain.MisMusicCollection;
import com.shycloud.mido.music.feign.MusicRemoteService;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.joy.zebra.common.push.JPushUtils;
import com.shycloud.common.minio.service.MinioTemplate;
import com.shycloud.mido.common.api.constants.HomeWorkConstants;
import com.shycloud.mido.common.api.vo.IPageWrapper;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.common.security.util.SecurityUtils;
import com.shycloud.mido.homework.api.dto.AssignDto;
import com.shycloud.mido.homework.api.entity.MidoHomeworkComment;
import com.shycloud.mido.homework.api.entity.MidoHomeworkComplate;
import com.shycloud.mido.homework.api.entity.MidoHomeworkMain;
import com.shycloud.mido.homework.api.entity.OrgRelationshipUnlinkLog;
import com.shycloud.mido.homework.api.enums.JPushCodeEnum;
import com.shycloud.mido.homework.api.feign.StudentFeignService;
import com.shycloud.mido.homework.api.feign.TeacherFeignService;
import com.shycloud.mido.homework.api.vo.AtvActiveDetailDataVO;
import com.shycloud.mido.homework.api.vo.AtvActiveDetailItemVO;
import com.shycloud.mido.homework.api.vo.AtvActiveDetailReqVO;
import com.shycloud.mido.homework.api.vo.AtvScheduleReqVO;
import com.shycloud.mido.homework.api.vo.AtvScheduleVO;
import com.shycloud.mido.homework.api.vo.HomeworkDashboardReqVO;
import com.shycloud.mido.homework.api.vo.MidoHomeworkMainVO;
import com.shycloud.mido.homework.api.vo.MusicNameVO;
import com.shycloud.mido.homework.api.vo.PlayDataVO;
import com.shycloud.mido.homework.mapper.MidoHomeworkCommentMapper;
import com.shycloud.mido.homework.mapper.MidoHomeworkMainMapper;
import com.shycloud.mido.homework.service.MidoHomeworkComplateService;
import com.shycloud.mido.homework.service.MidoHomeworkMainService;
import com.shycloud.mido.organ.api.enums.MessageCodeEnum;
import com.shycloud.mido.organ.api.util.Constant;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 作业业务相关接口 缺省-1期接口 V2-作业整合时期接口 V3-多师琴房时期接口
 *
 * @author nianhua.jiang
 * @date 2021/8/17 10:17
 */
@Slf4j
@Api(tags = "作业主接口")
@RestController
@AllArgsConstructor
@RequestMapping("/main")
public class HomeworkController {

	/** 七牛云 SDK 上传 */
	private final MinioTemplate minioTemplate;
	/** 作业模块 service */
	private final MidoHomeworkMainService mainService;
	/** 作业完成情况 service */
	private final MidoHomeworkComplateService complateService;
	/** 作业模块 mapper */
	private final MidoHomeworkMainMapper mainMapper;
	/** 作业点评 mapper */
	private final MidoHomeworkCommentMapper commentMapper;
	/** 教师 feign service */
	private final TeacherFeignService teacherFeignService;
	/** 学生 feign service */
	private final StudentFeignService studentFeignService;
	/** 用户 feign service */
	private final RemoteMemberService memberService;
	/** 曲目 feign service */
	private final MusicRemoteService musicRemoteService;
	private final static Log logger = LogFactory.getLog(HomeworkController.class);

	@ApiOperation("获取作业详情")
	@GetMapping("/detail")
	public R<MidoHomeworkMain> detail(Integer id) {
		MidoHomeworkMain item = mainMapper.selectById(id);
		return new R<>(item);
	}

	/**
	 * 学生点击更新提醒状态
	 *
	 * @param startDate 开始时间
	 * @return com.shycloud.mido.common.core.util.R
	 */
	@GetMapping("updateDing")
	public R<Integer> updateDing(String startDate) {
		return mainService.updateDing(startDate);
	}

	/**
	 * 删除单条作业
	 *
	 * @param id 作业ID
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/7/3 16:30
	 */
	@ApiOperation("删除单条作业")
	@GetMapping("/delete")
	public R<Boolean> delete(String id) {
		return new R<>(mainService.deleteHomework(id));
	}

	@ApiOperation("批量删除作业")
	@PostMapping("/deleteBatch")
	public R<Boolean> deleteBatch(@RequestBody List<String> idList) {
		return new R<>(mainService.deleteHomeworkBatch(idList));
	}


	@ApiOperation("批量删除作业")
	@PostMapping("/deleteBatchV2")
	public R<Boolean> deleteBatchV2(@RequestBody Map<String, Object> reqList) {
		return new R<>(mainService.deleteHomeworkBatchV2(reqList));
	}

	/**
	 * 教师获取学生作业列表
	 *
	 * @param current   当前页
	 * @param size      每页条数
	 * @param startDate 作业开始时间
	 * @param studentId 学生ID
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/28 13:26
	 */
	@ApiOperation("获取作业列表(分页)")
	@GetMapping("/getHomework")
	@Deprecated
	public R<IPageWrapper<MidoHomeworkMainVO>> page(Integer current, Integer size, String startDate, String studentId,
			Integer musicId, String isParentMode) {
		//是否是学生调用
		int incompleteNumber = 0;

		boolean isStudent = "-1".equals(studentId);

		//学生筛选曲目作业
		if ("-1".equals(studentId)) {
			//member_id
			String memberId = SecurityUtils.getMember().getId();
			//根据member_id获取学生ID
			studentId = studentFeignService.getStudentId(memberId);
		}
		IPageWrapper<MidoHomeworkMainVO> finalResult = new IPageWrapper<>(current, size);

		if (isStudent) {

			if (StringUtils.isNotBlank(isParentMode)) {
				if (StringUtils.equals("0", isParentMode)) {
					//学生 作业模式
					IPage<MidoHomeworkMainVO> pageParam = new Page<>(current, size);
					IPage<MidoHomeworkMainVO> resultPage = mainMapper
							.getHomeworkPage(pageParam, studentId, startDate, musicId, isParentMode,
									null);

					if (Objects.nonNull(resultPage)) {
						finalResult.setPages(resultPage.getPages());
						finalResult.setTotal(resultPage.getTotal());
						List<MidoHomeworkMainVO> tmpList = resultPage.getRecords();
						if (CollectionUtils.isNotEmpty(tmpList)) {
							tmpList.stream().sorted(Comparator
									.comparing(MidoHomeworkMainVO::getStatus,
											Comparator.reverseOrder())
									.thenComparing(MidoHomeworkMainVO::getCreateTime,
											Comparator.reverseOrder()));
							finalResult.setRecords(tmpList);
						}
					}

				} else if (StringUtils.equals("1", isParentMode)) {

					//学生 家长模式 自己留作业
					IPage<MidoHomeworkMainVO> pageParam = new Page<>(current, size);
					IPage<MidoHomeworkMainVO> resultPage = mainMapper
							.getHomeworkPage(pageParam, studentId, startDate, musicId, isParentMode,
									HomeWorkConstants.PARENT_MODE_TEACHER_ID);

					if (Objects.nonNull(resultPage)) {
						finalResult.setTotal(resultPage.getTotal());
						finalResult.setPages(resultPage.getPages());
						List<MidoHomeworkMainVO> tmpList = resultPage.getRecords();
						if (CollectionUtils.isNotEmpty(tmpList)) {
							//tmpList = tmpList.stream().sorted((n1, n2) -> Integer.parseInt(n1.getStatus()) - Integer.parseInt(n2.getStatus())).collect(Collectors.toList());
							tmpList.stream().sorted(Comparator
									.comparing(MidoHomeworkMainVO::getStatus,
											Comparator.reverseOrder())
									.thenComparing(MidoHomeworkMainVO::getCreateTime,
											Comparator.reverseOrder()));

							finalResult.setRecords(tmpList);
						}
					}
				}
			}

			//finalList.stream().sorted((n1, n2) -> n2.getId().compareTo(n1.getId())).collect(Collectors.toList());

			dealwithHomeworkList(finalResult.getRecords());

			//在最后处理未完成数量
			for (MidoHomeworkMainVO vo : finalResult.getRecords()) {
				//状态不等于2则为未完成
				if (!vo.getStatus().equals("2")) {
					incompleteNumber += 1;
				}
			}

			finalResult.setIncompleteNumber(incompleteNumber);
			finalResult.setRecords(finalResult.getRecords());
		} else {
			IPage<MidoHomeworkMainVO> pageParam = new Page<>(current, size);
			IPage<MidoHomeworkMainVO> resultPage = mainMapper.getHomeworkPage(pageParam,
					studentId, startDate, musicId, isParentMode,
					teacherFeignService.getCurTeacherIdByStu(studentId));
			List<MidoHomeworkMainVO> tmpList = resultPage.getRecords();
			if (CollectionUtils.isNotEmpty(tmpList)) {
				//tmpList = tmpList.stream().sorted((n1, n2) -> Integer.parseInt(n1.getStatus()) - Integer.parseInt(n2.getStatus())).collect(Collectors.toList());
				tmpList.stream().sorted(Comparator
						.comparing(MidoHomeworkMainVO::getStatus, Comparator.reverseOrder())
						.thenComparing(MidoHomeworkMainVO::getCreateTime,
								Comparator.reverseOrder()));
				finalResult.setRecords(tmpList);
			}

			finalResult.setTotal(resultPage.getTotal());

			dealwithHomeworkList(resultPage.getRecords());

			//在最后处理未完成数量
			for (MidoHomeworkMainVO vo : finalResult.getRecords()) {
				//状态不等于2则为未完成
				if (!vo.getStatus().equals("2")) {
					incompleteNumber += 1;
				}
			}
			finalResult.setIncompleteNumber(incompleteNumber);
			finalResult.setRecords(resultPage.getRecords());
			finalResult.setPages(resultPage.getPages());
		}
		return new R(finalResult);
	}

	private void dealwithHomeworkList(List<MidoHomeworkMainVO> homeworkList) {
		for (MidoHomeworkMainVO homework : homeworkList) {
			//在判断是否购买了此曲集
			Integer isBuy = mainMapper.getIsByCollection(SecurityUtils.getMember().getId(),
					homework.getCollectionId());
			//购买过此曲集
			if (isBuy != null) {
				homework.setIsVip("0");
			}
			//处理七牛云私有文件
			if (homework.getRecordingSrc() != null && homework.getRecordingSrc()
					.startsWith("http://mido.recording.v2.joymido.com")) {
				homework.setRecordingSrc(
						minioTemplate.getPrivateDownloadUrl(homework.getRecordingSrc()));
			}
		}
	}

	/**
	 * 教师获取学生作业列表
	 *
	 * @param current
	 * @param size
	 * @param startDate
	 * @param studentId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/28 13:26
	 */
	@ApiOperation("获取作业列表(分页)")
	@GetMapping("/getHomeworkPlayer")
	public R getHomeworkPlayer(String isParentMode, Integer current, Integer size, String startDate,
			String studentId, Integer musicId) {
		//是否是学生调用
		boolean isStudent = ("-1".equals(studentId)) ? true : false;

		//学生筛选曲目作业
		if ("-1".equals(studentId)) {
			//member_id
			String memberId = SecurityUtils.getMember().getId();
			//根据member_id获取学生ID
			studentId = studentFeignService.getStudentId(memberId);
		}

		//分页参数
		Page page = new Page(current, size);
		List<MidoHomeworkMainVO> finalList = new ArrayList<>();
		//家长模式作业获取
		if ("0".equals(isParentMode)) {

		} else {
			finalList = mainMapper.getHomeworkPlayer(
					studentId, startDate, musicId, HomeWorkConstants.PARENT_MODE_TEACHER_ID, "1");
		}

		IPageWrapper<MidoHomeworkMainVO> finalResult = new IPageWrapper<>(current, size);
		finalResult.setRecords(finalList);
		finalResult.setTotal(finalList.size());

		//如果是学生，则获取所有历史老师的作业和自己的家长模式作业
		//如果是老师，则只获取自己布置的作业
		if (isStudent) {
			//选取现在所有的老师记录
			List<String> teacherIdList = teacherFeignService.getTeacherIdsByStudentId(studentId);
			//选取之前解绑的老师记录
			List<OrgRelationshipUnlinkLog> unlinkTeacherLogs = teacherFeignService
					.getUniqueTeacherUnlinkLog(studentId);

			if (unlinkTeacherLogs != null && unlinkTeacherLogs.size() != 0) {
				for (OrgRelationshipUnlinkLog log : unlinkTeacherLogs) {
					for (String teacherId : teacherIdList) {
						if (!teacherId.equals(log.getTeacherId())) {
							List<MidoHomeworkMainVO> tmpList = mainMapper.getHomeworkPlayer(
									studentId, startDate, musicId, log.getTeacherId(),
									isParentMode);
							finalList.addAll(tmpList);
							finalResult.setTotal(finalResult.getTotal() + tmpList.size());
						}
					}
				}
			}

			if (teacherIdList != null && teacherIdList.size() != 0) {
				for (int i = 0; i < teacherIdList.size(); i++) {
					String teacherId = teacherIdList.get(i);
					List<MidoHomeworkMainVO> tmpList = mainMapper.getHomeworkPlayer(
							studentId, startDate, musicId, teacherId, isParentMode);

					finalList.addAll(tmpList);
					finalResult.setTotal(finalResult.getTotal() + tmpList.size());
				}
			}

			finalList.stream().sorted((n1, n2) -> n2.getId().compareTo(n1.getId()))
					.collect(Collectors.toList());

			int curSize = finalList.size();
			int startOffset = size * (current - 1);
			int endOffset = size * current;
			finalResult.setRecords(curSize < startOffset ?
					new ArrayList<>()
					: (curSize <= endOffset ? finalList.subList(startOffset, curSize)
							: finalList.subList(startOffset, endOffset)));
		} else {
			List<MidoHomeworkMainVO> tmpList = mainMapper.getHomeworkPlayer(
					studentId, startDate, musicId,
					teacherFeignService.getCurTeacherIdByStu(studentId), isParentMode);

			finalList.addAll(tmpList);
			finalResult.setTotal(finalResult.getTotal() + tmpList.size());

			finalList.stream().sorted((n1, n2) -> n2.getId().compareTo(n1.getId()))
					.collect(Collectors.toList());

			int curSize = finalList.size();
			int startOffset = size * (current - 1);
			int endOffset = size * current;
			finalResult.setRecords(curSize < startOffset ?
					new ArrayList<>()
					: (curSize <= endOffset ? finalList.subList(startOffset, curSize)
							: finalList.subList(startOffset, endOffset)));
		}

		int totalPages =
				finalList.size() == 0 ? 0 : new Long(finalList.size() / size).intValue() + 1;
		finalResult.setPages(totalPages);

		return new R(finalResult);
	}

	/**
	 * 学生弹琴时播放器内作业列表 - 支持多师琴房
	 *
	 * @param current
	 * @param size
	 * @param startDate
	 * @param studentId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/28 13:26
	 */
	@ApiOperation("播放器内获取作业列表 - 支持多师琴房")
	@GetMapping("/getHomeworkPlayerV3")
	public R getHomeworkPlayerV3(Integer current, Integer size,
			String startDate,
			String studentId,
			Integer musicId,
			String teacherId,
			String classroomId) {

		//定义教师集合
		List<String> teacherIds = new ArrayList<>();
		//定义返回的结构体
		IPageWrapper<MidoHomeworkMainVO> finalResult = new IPageWrapper<>(current, size);

		if (StringUtils.isNotBlank(teacherId)) {
			teacherIds.add(teacherId);
		} else if (StringUtils.isNotBlank(classroomId)) {
			//根据班级ID获取教师集合
			List<MyTeacherVO> teachers = memberService.getTeacherListByRoomIdFeign(classroomId);
			if (CollectionUtils.isEmpty(teachers)) {
				//如果没查到教师,则返回空作业列表
				return new R(finalResult);
			} else {
				List<String> teacherIdsFeign = teachers.stream().map(x -> x.getTeacherId()).collect(Collectors.toList());
				teacherIds.addAll(teacherIdsFeign);
			}
		}

		//学生筛选曲目作业
		if ("-1".equals(studentId)) {
			//member_id
			String memberId = SecurityUtils.getMember().getId();
			//根据member_id获取学生ID
			studentId = studentFeignService.getStudentId(memberId);
		}

		//分页参数
		Page page = new Page(current, size);

		return new R(mainMapper.getHomeworkPlayerV3(page, studentId, startDate, musicId, teacherIds));
	}

	/**
	 * 教师下发作业
	 *
	 * @param assignDto
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/24 11:27
	 */
	@ApiOperation("下发作业")
	@PostMapping("/assign")
	public R assign(@RequestBody AssignDto assignDto) {

		//判断画笔参数大小，如果超出限制，则给出错误信息。
		String paramsJsonPen = assignDto.getParamsJsonPen();
		if (paramsJsonPen != null) {
			byte[] bytesPen = paramsJsonPen.getBytes();
			if (bytesPen.length > (5 * 1024 * 1024)) {
				return new R(CommonConstants.FAIL, "您批注的地方过多，无法下发作业", false);
			}
		}

		String paramsJsonFont = assignDto.getParamsJsonFont();
		if (paramsJsonFont != null) {
			byte[] bytesFont = paramsJsonFont.getBytes();
			if (bytesFont.length > (5 * 1024 * 1024)) {
				return new R(CommonConstants.FAIL, "您批注的地方过多，无法下发作业", false);
			}
		}

		if (assignDto.getStartRhythm() <= 0 || assignDto.getEndRhythm() <= 0) {
			assignDto.setStartRhythm(0);
			assignDto.setEndRhythm(0);
		}

		//feign调用获取教师ID
		if (StringUtils.isEmpty(assignDto.getTeacherId())) {
			String teacherId = teacherFeignService.getTeacherId(assignDto.getOrgId());
			if (teacherId != null) {
				assignDto.setTeacherId(teacherId);
			} else {
				return new R(CommonConstants.FAIL, "教师信息获取失败", false);
			}
		}
		//前端传输的music是毫秒，需要 （/1000） 转化成秒
		if (StringUtils.isNotBlank(assignDto.getMusicLength())) {
			assignDto.setMusicLength(String.valueOf(Double.valueOf(assignDto.getMusicLength()) / 1000));
		}

		//插入曲集封面
		MisMusicCollection misMusicCollection = musicRemoteService.getCollByMusicIdFeign(assignDto.getMusicId());
		assignDto.setImg(misMusicCollection.getImg());

		return mainService.assign(assignDto);
	}

	private boolean checkAssignRestrictRule(String studentId) {
		Map assignBalMap = studentFeignService.getStudentAssignBal(studentId);

		if (assignBalMap == null) {
			return false;
		}

		if (assignBalMap.get("curAssignBal") == null) {
			return false;
		}
		if (assignBalMap.get("nextAssignBal") == null) {
			return false;
		}

		if ((Integer) assignBalMap.get("curAssignBal") < 0) {
			return false;
		}
		if ((Integer) assignBalMap.get("nextAssignBal") < 0) {
			return false;
		}

		return true;
	}

	/**
	 * 家长模式下发作业
	 *
	 * @param assignDto
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/8/24 10:30
	 */
	@ApiOperation("家长模式下发作业")
	@PostMapping("/assignForParent")
	public R assignForParent(@RequestBody AssignDto assignDto) {
		//判断画笔参数大小，如果超出限制，则给出错误信息。
		String paramsJsonPen = assignDto.getParamsJsonPen();
		if (paramsJsonPen != null) {
			byte[] bytesPen = paramsJsonPen.getBytes();
			if (bytesPen.length > (64 * 1024)) {
				return new R(CommonConstants.FAIL, "您批注的地方过多，无法下发作业", false);
			}
		}

		String paramsJsonFont = assignDto.getParamsJsonFont();
		if (paramsJsonFont != null) {
			byte[] bytesFont = paramsJsonFont.getBytes();
			if (bytesFont.length > (64 * 1024)) {
				return new R(CommonConstants.FAIL, "您批注的地方过多，无法下发作业", false);
			}
		}

//		//检查学生可用下发额度
//		if (!checkAssignRestrictRule(assignDto.getStudentId())) {
//			new R(CommonConstants.FAIL, "该学生作业分配数量已超最大限制, 若想留更多作业请联系客服!", false);
//		}

		if (assignDto.getStartRhythm() <= 0 || assignDto.getEndRhythm() <= 0) {
			assignDto.setStartRhythm(0);
			assignDto.setEndRhythm(0);
		}

		//插入曲集封面
		MisMusicCollection misMusicCollection = musicRemoteService.getCollByMusicIdFeign(assignDto.getMusicId());
		assignDto.setImg(misMusicCollection.getImg());

		//feign调用获取学生ID
		String studentId = studentFeignService.getStudentId(SecurityUtils.getMember().getId());
		if (studentId != null) {
			assignDto.setStudentId(studentId);
			return mainService.assignForParent(assignDto);
		}

		return new R(CommonConstants.FAIL, "学生信息获取失败", false);
	}

	/**
	 * 提交作业
	 *
	 * @param complate
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/28 16:30
	 */
//	@ApiOperation("提交作业")
//	@PostMapping("/submitHomwork")
//	public R submit(@RequestBody MidoHomeworkComplateVO complate) {
//		return new R(complateService.submitHomwork(complate));
//	}

	/**
	 * 提交作业
	 *
	 * @param complate
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/28 16:30
	 */
	@ApiOperation("提交作业")
	@PostMapping("/submitHomwork")
	public R submitHomworkWeek(@RequestBody MidoHomeworkComplateVO complate) {
		return new R(complateService.submitHomworkWeek(complate));
	}

	/**
	 * 提交未完成的作业
	 *
	 * @param complate
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/28 16:30
	 */
	@ApiOperation("提交未完成的作业")
	@PostMapping("/submitHomworkNon")
	public R submitHomworkNon(@RequestBody MidoHomeworkComplateVO complate) {
		complate.setCreateTime(new Date());
		return new R(complateService.submitHomworkWeekNon(complate));
	}


	/**
	 * 获取最近一次的作业模式(废弃)
	 *
	 * @param
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/7/3 10:10
	 */
	@Deprecated
	@ApiOperation("获取最近一次的作业模式")
	@GetMapping("getLatelyHomework")
	public R getLatelyHomework(Integer musicId) {

		//获取学生id
		String studentId = studentFeignService.getStudentId(SecurityUtils.getMember().getId());

		List<MidoHomeworkMain> homeworkMainList = mainService
				.list(new QueryWrapper<MidoHomeworkMain>()
						.eq(MidoHomeworkMain.COL_MUSIC_ID, musicId)
						.and(x -> x.eq(MidoHomeworkMain.COL_STUDENT_ID, studentId))
						.orderByDesc(MidoHomeworkMain.COL_START_DATE));

		if (homeworkMainList.size() > 0 && homeworkMainList.get(0) != null) {
			MidoHomeworkMainVO midoHomeworkMainVO = new MidoHomeworkMainVO();

			BeanUtils.copyProperties(homeworkMainList.get(0), midoHomeworkMainVO);

			//获取教师姓名
			String teacherName = mainService.getTeacherName(homeworkMainList.get(0).getTeacherId());

			midoHomeworkMainVO.setTeacherName(teacherName);

			return new R(midoHomeworkMainVO);
		}
		return new R(CommonConstants.FAIL, "暂无最近的作业", false);
	}

	/**
	 * 上传录音(作业/点评)
	 *
	 * @param file
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/29 14:29
	 */
	@ApiOperation("上传录音(作业/点评)")
	@PostMapping("/uploadRecord")
	public R uploadRecord(@RequestParam(value = "File") MultipartFile file) {
		String path = Constant.PRA_URL_TAPE;
		String url;
		String fileName = path + IdUtil.simpleUUID() + StrUtil.DOT + FileUtil
				.extName(file.getOriginalFilename());
		try {
			url = minioTemplate.uploadFile(file.getInputStream(), fileName, "mido-recording");
		} catch (IOException e) {
			return new R<>(MessageCodeEnum.MEMBER_ERROR_101.getCode(),
					MessageCodeEnum.MEMBER_ERROR_101.getMessage(), null);
		}
		return new R<>(url, MessageCodeEnum.SUCCESS.getMessage());
	}

	@ApiOperation("点评作业")
	@PostMapping("/comment")
	public R comment(@RequestBody MidoHomeworkComment comment) {
		return new R(commentMapper.insert(comment));
	}

	/**
	 * 获取最近七天的作业完成情况
	 *
	 * @param startDate
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/7/3 17:39
	 */
	@ApiOperation("获取最近七天的作业完成情况")
	@GetMapping("getHomework7Days")
	public R getHomework7Days(String startDate, String studentId) {
		//是否是学生调用
		boolean isStudent = ("-1".equals(studentId)) ? true : false;
		return mainService.getHomework7Days(startDate, studentId, isStudent);
	}

	/**
	 * 获取最近七天的作业完成情况
	 *
	 * @param startDate
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/7/3 17:39
	 */
	@ApiOperation("获取最近一个月的作业完成情况")
	@GetMapping("getHomeworkMonth")
	public R getHomeworkMonth(String startDate, String studentId, String isParentMode) {
		//是否是学生调用
		boolean isStudent = ("-1".equals(studentId)) ? true : false;
		try {
			return mainService
					.getHomeworkMonthByThread(startDate, studentId, isStudent, isParentMode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new R(CommonConstants.FAIL, "查询失败", false);
	}

	/**
	 * 新版作业完成情况-月面板
	 *
	 * @param vo
	 * @return
	 * @author baiqiang.
	 * @date 2021年7月19日 下午2:12:33
	 * @version V1.0
	 */
	@ApiOperation("获取最近一个月的作业完成情况V2")
	@GetMapping("getHomeworkMonthV2")
	public R getHomeworkMonthV2(HomeworkDashboardReqVO vo) {
		try {
			return mainService.getHomeworkMonthByThreadV2(vo);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return new R(CommonConstants.FAIL, "查询失败", false);
	}


	/**
	 * 教师提醒学生作业
	 *
	 * @param homeworkId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/7/5 10:58
	 */
	@GetMapping("remindStudent")
	@ApiOperation("教师提醒学生作业")
	public R ding(String homeworkId) {

		//查询学生作业详情
		MidoHomeworkMain midoHomeworkMain = mainService.getById(homeworkId);
		//更新提醒状态
		midoHomeworkMain.setDing("1");

		return new R(mainService.updateById(midoHomeworkMain));
	}

	/**
	 * 教师提醒学生作业
	 *
	 * @param startDate
	 * @param teacherId
	 * @param studentId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/7/5 10:58
	 */
	@GetMapping("remindStudentV2")
	@ApiOperation("教师提醒学生作业")
	public R dingV2(String startDate, String teacherId, String studentId) {

		//查询学生作业详情
		List<MidoHomeworkMain> midoHomeworkMainList = mainMapper
				.getHomeWorkDingDetail(startDate.substring(0, 10), teacherId, studentId);

		if (midoHomeworkMainList.size() == 0) {
			return new R(CommonConstants.FAIL, "没有给该学生布置这一天的作业", false);
		}

		//更新提醒状态
		midoHomeworkMainList.forEach(x -> x.setDing("1"));

		boolean resultPush = false;

		if (mainService.updateBatchById(midoHomeworkMainList)) {

			resultPush = true;
			logger.info("======== 更新ding成功,执行定期推送业务 ====>");
			// 另起线程执行推送
			Thread thread = new Thread() {
				//******************** 执行推送提醒学生完成作业 ***********************//
				public void run() {

					// 获取学生的 regId 进行推送
					String regId = mainService.getRegIdByStudentId(studentId);
					// 根据学生 ID 获取 memberId
					String memberId = mainMapper.getMemberIdByStudentId(studentId);

					// 提醒学生
					JPushUtils.sendJMessage(JPushCodeEnum.J_PUSH_TEACHER_DING_STUDENT.getType(),
							regId, "NB");

					if (regId != null) {
						// 插入带提醒表，每日18点准时推送
						mainMapper.insertPushQuertz(memberId, studentId, teacherId,
								JPushCodeEnum.J_PUSH_TEACHER_DING_STUDENT.getType());
					}
				}
			};

			thread.start();
		}

		return new R(resultPush);
	}

	/**
	 * 获取作业筛选列表
	 *
	 * @param startDate
	 * @param studentId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/7/8 9:35
	 */
	@GetMapping("getHomeworkMusicList")
	@ApiOperation("获取作业筛选列表")
	public R getHomeworkMusicList(String startDate, String studentId, String isParentMode) {
		//是否是学生调用
		boolean isStudent = ("-1".equals(studentId)) ? true : false;

		//学生筛选曲目作业
		if ("-1".equals(studentId)) {
			//member_id
			String memberId = SecurityUtils.getMember().getId();
			//根据member_id获取学生ID
			studentId = studentFeignService.getStudentId(memberId);
		}

		List<MusicNameVO> resultList = new ArrayList<>();
		//家长模式的作业
		if (isParentMode == null || "1".equals(isParentMode)) {
			resultList = mainService
					.getHomeworkMusicList(studentId, startDate, HomeWorkConstants.PARENT_MODE_TEACHER_ID);
			return new R(resultList);
		}

		if (isStudent) {
			//选取现在所有的老师记录
			List<String> teacherIdList = teacherFeignService.getTeacherIdsByStudentId(studentId);
			//选取之前解绑的老师记录
			List<OrgRelationshipUnlinkLog> unlinkTeacherLogs = teacherFeignService
					.getUniqueTeacherUnlinkLog(studentId);

			if (unlinkTeacherLogs != null && unlinkTeacherLogs.size() != 0) {
				for (OrgRelationshipUnlinkLog log : unlinkTeacherLogs) {
					for (String teacherId : teacherIdList) {
						if (!teacherId.equals(log.getTeacherId())) {
							resultList.addAll(mainMapper.getHomeworkMusicList(studentId, startDate,
									log.getTeacherId()));
						}
					}

					//学生还未绑定教师，也要显示之前老师留的作业
					if (teacherIdList.size() == 0) {
						resultList.addAll(mainMapper
								.getHomeworkMusicList(studentId, startDate, log.getTeacherId()));
					}

				}
			}

			if (teacherIdList != null && teacherIdList.size() != 0) {
				for (int i = 0; i < teacherIdList.size(); i++) {
					List<MusicNameVO> tempList = mainService
							.getHomeworkMusicList(studentId, startDate, teacherIdList.get(i));
					resultList.addAll(tempList);
				}
			}

			resultList.stream().sorted((n1, n2) -> n2.getMusicId().compareTo(n1.getMusicId()))
					.collect(Collectors.toList());

			return new R(resultList);
		} else {
			resultList.addAll(
					mainService.getHomeworkMusicList(studentId, startDate,
							teacherFeignService.getCurTeacherIdByStu(studentId)));

			return new R(resultList);
		}
	}

	/**
	 * 获取作业筛选列表 - 支持多师琴房
	 *
	 * @param startDate
	 * @param studentId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2021/8/10 16:50
	 */
	@ApiOperation("获取作业筛选列表")
	@GetMapping("getHomeworkMusicListV3")
	public R getHomeworkMusicListV3(String startDate, String studentId, String isParentMode, String classroomId, String teacherId) {

		//定义返回的结构体
		List<MusicNameVO> resultList = new ArrayList<>();
		//定义教师集合
		List<String> teacherIds = new ArrayList<>();

		if (StringUtils.isNotBlank(teacherId)) {
			teacherIds.add(teacherId);
		} else if (StringUtils.isNotBlank(classroomId)) {
			//根据班级ID获取教师集合
			List<MyTeacherVO> teachers = memberService.getTeacherListByRoomIdFeign(classroomId);
			if (CollectionUtils.isEmpty(teachers)) {
				//如果没查到教师,则返回空作业列表
				return new R(resultList);
			} else {
				List<String> teacherIdsFeign = teachers.stream().map(x -> x.getTeacherId()).collect(Collectors.toList());
				teacherIds.addAll(teacherIdsFeign);
			}
		}

		//学生筛选曲目作业
		if ("-1".equals(studentId)) {
			//member_id
			String memberId = SecurityUtils.getMember().getId();
			//根据member_id获取学生ID
			studentId = studentFeignService.getStudentId(memberId);
		}

		//家长模式的作业
		if (isParentMode == null || "1".equals(isParentMode)) {
			resultList = mainService.getHomeworkMusicList(studentId, startDate, HomeWorkConstants.PARENT_MODE_TEACHER_ID);
			return new R(resultList);
		}

		//教师留的作业
		resultList.addAll(mainMapper.getHomeworkMusicListV3(studentId, startDate, teacherIds));

		resultList.stream().sorted((n1, n2) -> n2.getMusicId().compareTo(n1.getMusicId()))
				.collect(Collectors.toList());

		return new R(resultList);

	}

	//Added

	/**
	 * 上传学生弹奏记录数据
	 *
	 * @param playDataVO
	 * @return com.shycloud.mido.common.core.util.R
	 * @author xiaoxing.yu
	 * @date 2020/7/8 9:35
	 */
	@PostMapping("uploadPlayData")
	@ApiOperation("上传学生弹奏记录数据")
	public R uploadPlayOperationData(@RequestBody PlayDataVO playDataVO) {
		//学生筛选曲目作业
		//member_id
		String memberId = SecurityUtils.getMember().getId();
		//根据member_id获取学生ID
		String studentId = studentFeignService.getStudentId(memberId);
		playDataVO.setStudentId(studentId);

		return new R(mainService.uploadPlayData(playDataVO, memberId));
	}

	//Added

	/**
	 * 获取学生弹奏记录数据
	 *
	 * @param homeworkId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author xiaoxing.yu
	 * @date 2020/7/8 9:35
	 */
	@GetMapping("getPlayData")
	@ApiOperation("获取学生弹奏记录数据")
	public R getPlayOperationData(String homeworkId) {
		return new R(mainService.getPlayData(homeworkId));
	}

	/**
	 * 获取文件上传的凭证
	 *
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/11/27 10:16
	 **/
	@GetMapping("getUploadToken")
	public R getUploadToken(String bucketName) {
		Map<String, Object> resultMap = new HashMap<>();
		//long overTime = 3600;
		if (StringUtils.isEmpty(bucketName)) {
			resultMap.put("token", minioTemplate.getPrivateUploadToken("mido-recording-v2", null));
		} else {
			resultMap.put("token", minioTemplate.getPrivateUploadToken(bucketName, null));
		}

		resultMap.put("overTime", 3600);
		return new R(resultMap);
	}

	/**
	 * (小程序使用)
	 *
	 * @param page
	 * @param startDate
	 * @param musicId
	 * @param isParentMode
	 * @param teacherId
	 * @param studentId
	 * @return
	 */
	@GetMapping("getStudentHomework")
	public R getStudentHomework(Page page, String startDate, Integer musicId, String isParentMode,
			String teacherId, String studentId) {
		Long current = page.getCurrent();
		Long size = page.getSize();
		IPageWrapper<MidoHomeworkMainVOMini> finalResult = new IPageWrapper<>(current, size);

		int incompleteNumber = 0;
		//是否是学生调用
		boolean isStudent = ("-1".equals(studentId)) ? true : false;

		if (StringUtils.isBlank(studentId)) {
			//没有的话取一个默认学生
			List<Map<String, String>> list = (List) studentFeignService.getStudentList(teacherId)
					.getData();
			studentId = list.get(0).get("studentId");

			IPage<MidoHomeworkMainVOMini> pageParam = new Page<>(current, size);
			IPage<MidoHomeworkMainVOMini> resultPage = mainMapper
					.getHomeworkPageMini(pageParam, studentId, startDate, musicId, isParentMode,
							teacherId);
			if (Objects.nonNull(resultPage)) {
				finalResult.setPages(resultPage.getPages());
				finalResult.setTotal(resultPage.getTotal());
				List<MidoHomeworkMainVOMini> tmpList = resultPage.getRecords();
				if (CollectionUtils.isNotEmpty(tmpList)) {
					tmpList = tmpList.stream()
							.sorted((n1, n2) -> Integer.parseInt(n1.getStatus()) - Integer
									.parseInt(n2.getStatus())).collect(Collectors.toList());
					finalResult.setRecords(tmpList);
				}
			}
			return new R(finalResult);

		}

		//-1表示学生调用此接口
		if ("-1".equals(studentId)) {
			//member_id
			String memberId = SecurityUtils.getMember().getId();
			//根据member_id获取学生ID
			studentId = studentFeignService.getStudentId(memberId);
		}

		if (isStudent) {

			if (StringUtils.isNotBlank(isParentMode)) {
				if (StringUtils.equals("0", isParentMode)) {
					//学生 作业模式
					IPage<MidoHomeworkMainVOMini> pageParam = new Page<>(current, size);
					IPage<MidoHomeworkMainVOMini> resultPage = mainMapper
							.getHomeworkPageMini(pageParam, studentId, startDate, musicId, isParentMode,
									null);

					if (Objects.nonNull(resultPage)) {
						finalResult.setPages(resultPage.getPages());
						finalResult.setTotal(resultPage.getTotal());
						List<MidoHomeworkMainVOMini> tmpList = resultPage.getRecords();
						if (CollectionUtils.isNotEmpty(tmpList)) {
							tmpList = tmpList.stream()
									.sorted((n1, n2) -> Integer.parseInt(n1.getStatus()) - Integer
											.parseInt(n2.getStatus())).collect(Collectors.toList());
							finalResult.setRecords(tmpList);
						}
					}

				} else if (StringUtils.equals("1", isParentMode)) {

					//学生 家长模式 自己留作业
					IPage<MidoHomeworkMainVOMini> pageParam = new Page<>(current, size);
					IPage<MidoHomeworkMainVOMini> resultPage = mainMapper
							.getHomeworkPageMini(pageParam, studentId, startDate, musicId, isParentMode,
									HomeWorkConstants.PARENT_MODE_TEACHER_ID);

					if (Objects.nonNull(resultPage)) {
						finalResult.setPages(resultPage.getPages());
						finalResult.setTotal(resultPage.getTotal());
						List<MidoHomeworkMainVOMini> tmpList = resultPage.getRecords();
						if (CollectionUtils.isNotEmpty(tmpList)) {
							tmpList = tmpList.stream()
									.sorted((n1, n2) -> Integer.parseInt(n1.getStatus()) - Integer
											.parseInt(n2.getStatus())).collect(Collectors.toList());
							finalResult.setRecords(tmpList);
						}
					}

				}
			}

			//在最后处理未完成数量
			for (MidoHomeworkMainVOMini vo : finalResult.getRecords()) {
				//状态不等于2则为未完成
				if (!vo.getStatus().equals("2")) {
					incompleteNumber += 1;
				}
			}
			finalResult.setIncompleteNumber(incompleteNumber);
		} else {
			IPage<MidoHomeworkMainVOMini> pageParam = new Page<>(current, size);
			IPage<MidoHomeworkMainVOMini> resultPage = mainMapper.getHomeworkPageMini(pageParam,
					studentId, startDate, musicId, isParentMode,
					teacherFeignService.getCurTeacherIdByStu(studentId));

			if (Objects.nonNull(resultPage)) {
				finalResult.setPages(resultPage.getPages());
				finalResult.setTotal(resultPage.getTotal());
				List<MidoHomeworkMainVOMini> tmpList = resultPage.getRecords();
				if (CollectionUtils.isNotEmpty(tmpList)) {
					tmpList = tmpList.stream()
							.sorted((n1, n2) -> Integer.parseInt(n1.getStatus()) - Integer
									.parseInt(n2.getStatus())).collect(Collectors.toList());
					finalResult.setRecords(tmpList);
				}
			}

			//在最后处理未完成数量
			for (MidoHomeworkMainVOMini vo : finalResult.getRecords()) {
				//状态不等于2则为未完成
				if (!vo.getStatus().equals("2")) {
					incompleteNumber += 1;
				}
			}
			finalResult.setIncompleteNumber(incompleteNumber);
		}
		return new R(finalResult);
	}

	/**
	 * (小程序使用)
	 *
	 * @param studentId
	 * @param startDate
	 * @return
	 */
	@GetMapping("getStudentTodayMusic")
	public R getStudentTodayMusic(String studentId, String startDate) {

		Map result = new HashMap<>();
		List<MidoHomeworkMainVO> todayHomework = new ArrayList<MidoHomeworkMainVO>();
		//是否是学生调用
		boolean isStudent = ("-1".equals(studentId)) ? true : false;
		List<Map> todayMusic = new ArrayList<Map>();
		Set<Map> todayMusicSet = new HashSet();

		//-1表示学生调用此接口
		if ("-1".equals(studentId)) {
			//member_id
			String memberId = SecurityUtils.getMember().getId();
			//根据member_id获取学生ID
			studentId = studentFeignService.getStudentId(memberId);
		}

		if (isStudent) {

			List<MidoHomeworkMainVO> tmpList = mainMapper
					.getHomework(studentId, startDate, null, "0", null);

			if (CollectionUtils.isNotEmpty(tmpList)) {
				todayHomework.addAll(tmpList);
			}
			List<Map> tmpMusicList = mainMapper.getStudentTodayMusic(studentId, startDate, null);
			if (CollectionUtils.isNotEmpty(tmpMusicList)) {
				todayMusic.addAll(tmpMusicList);
			}


		} else {
			String curTeacherId = teacherFeignService.getCurTeacherIdByStu(studentId);

			List<MidoHomeworkMainVO> tmpList = mainMapper.getHomework(
					studentId, startDate, null, "0", curTeacherId);

			if (CollectionUtils.isNotEmpty(tmpList)) {
				todayHomework.addAll(tmpList);
			}

			List<Map> tmpMusicList = mainMapper
					.getStudentTodayMusic(studentId, startDate, curTeacherId);
			if (CollectionUtils.isNotEmpty(tmpMusicList)) {
				todayMusic.addAll(tmpMusicList);
			}
		}

		//结果合并去重
		todayMusicSet.addAll(todayMusic);

		Object[] mapArr = todayMusicSet.toArray();
		todayMusic = new ArrayList<>();
		for (int j = 0; j < mapArr.length; j++) {
			todayMusic.add((Map) mapArr[j]);
		}

		result.put("total", todayHomework.size());
		result.put("music", todayMusic);
		return new R(result);
	}

	/**
	 * 教师获取学生作业列表
	 *
	 * @param startDate
	 * @param studentId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/28 13:26
	 */
	@ApiOperation("获取作业列表(分页)")
	@GetMapping("/getHomeworkV2")
	public R getHomeworkV2(String startDate, String studentId, Integer musicId, String isParentMode,
			String isAllOk) {

		//是否是学生调用
		boolean isStudent = ("-1".equals(studentId)) ? true : false;

		//学生筛选曲目作业
		if ("-1".equals(studentId)) {
			//member_id
			String memberId = SecurityUtils.getMember().getId();
			//根据member_id获取学生ID
			studentId = studentFeignService.getStudentId(memberId);
		}

		List<MidoHomeworkMainVO> finalList = new ArrayList<>();

		if (isStudent) {

			if (StringUtils.isNotBlank(isParentMode)) {
				if (StringUtils.equals("0", isParentMode)) {
					//学生 作业模式
					List<MidoHomeworkMainVO> tmpList = mainMapper
							.getHomework(studentId, startDate, musicId, isParentMode, null);
					if (CollectionUtils.isNotEmpty(tmpList)) {
						finalList.addAll(tmpList);
					}

				} else if (StringUtils.equals("1", isParentMode)) {

					//学生 家长模式 自己留作业
					List<MidoHomeworkMainVO> tmpList = mainMapper
							.getHomework(studentId, startDate, musicId, isParentMode,
									HomeWorkConstants.PARENT_MODE_TEACHER_ID);
					if (CollectionUtils.isNotEmpty(tmpList)) {
						finalList.addAll(tmpList);
					}
				}
			}


		} else {
			//老师 作业模式
			List<MidoHomeworkMainVO> tmpList = mainMapper.getHomework(
					studentId, startDate, musicId, isParentMode,
					teacherFeignService.getCurTeacherIdByStu(studentId));

			if (CollectionUtils.isNotEmpty(tmpList)) {
				finalList.addAll(tmpList);
			}

		}

		finalList.stream().sorted((n1, n2) -> n2.getId().compareTo(n1.getId()))
				.collect(Collectors.toList());

		dealwithHomeworkList(finalList);

		//取出所有的 groupId
		List<Long> groupIdSet = finalList.stream()
				.sorted(Comparator.comparing(MidoHomeworkMainVO::getCreateTime))
				.map(MidoHomeworkMainVO::getGroupId).distinct().collect(Collectors.toList());

		List<MidoHomeworkMainVO> resultList = new ArrayList<>();

		//新增整合逻辑，将单条作业整合成一组，以各个模式区分
		for (Long groupId : groupIdSet) {

			//试听模式数据（理论上集合大小为 1 或 0 ）
			List<MidoHomeworkMainVO> mode0 = finalList.stream()
					.filter(n -> groupId.equals(n.getGroupId()) && "0".equals(n.getPlayingMode()))
					.collect(Collectors.toList());

			if (mode0 != null && mode0.size() != 0) {
				MidoHomeworkMainVO mode0Temp = mode0.get(0);
				mode0Temp.setTargetGroupCount(mode0Temp.getTargetScore());
				mode0Temp.setOkGroupCount(mode0Temp.getOkCountOrScore());

				if (mode0.stream().anyMatch(x -> "1".equals(x.getDing()))) {
					mode0Temp.setDing("1");
				}

				resultList.add(mode0Temp);
			}

			//识谱模式作业
			List<MidoHomeworkMainVO> mode1 = finalList.stream()
					.filter(n -> groupId.equals(n.getGroupId()) && "1".equals(n.getPlayingMode()))
					.collect(Collectors.toList());

			//识谱模式已完成作业
			List<MidoHomeworkMainVO> mode1Ok = finalList.stream()
					.filter(n -> groupId.equals(n.getGroupId()) && "1".equals(n.getPlayingMode())
							&& "2".equals(n.getStatus()))
					.collect(Collectors.toList());

			//识谱模式未完成作业
			List<MidoHomeworkMainVO> mode1NotOk = finalList.stream()
					.filter(n -> groupId.equals(n.getGroupId()) && "1".equals(n.getPlayingMode())
							&& "0".equals(n.getStatus()))
					.collect(Collectors.toList());

			if (mode1 != null && mode1.size() != 0) {

				MidoHomeworkMainVO mode1Temp = null;

				if (mode1.size() != mode1Ok.size()) {
					mode1Temp = mode1NotOk.get(0);
					mode1Temp.setStatus("1");
				} else {
					mode1Temp = mode1Ok.get(0);
				}

				mode1Temp.setTargetGroupCount(mode1.size());
				mode1Temp.setOkGroupCount(mode1Ok.size());

				if (mode1.stream().anyMatch(x -> "1".equals(x.getDing()))) {
					mode1Temp.setDing("1");
				}

				resultList.add(mode1Temp);
			}

			//纠错模式作业
			List<MidoHomeworkMainVO> mode2 = finalList.stream()
					.filter(n -> groupId.equals(n.getGroupId()) && "2".equals(n.getPlayingMode()))
					.collect(Collectors.toList());

			//纠错模式已完成作业
			List<MidoHomeworkMainVO> mode2Ok = finalList.stream()
					.filter(n -> groupId.equals(n.getGroupId()) && "2".equals(n.getPlayingMode())
							&& "2".equals(n.getStatus()))
					.collect(Collectors.toList());

			//纠错模式未完成作业
			List<MidoHomeworkMainVO> mode2NotOk = finalList.stream()
					.filter(n -> groupId.equals(n.getGroupId()) && "2".equals(n.getPlayingMode())
							&& "0".equals(n.getStatus()))
					.collect(Collectors.toList());

			if (mode2 != null && mode2.size() != 0) {

				//挑选未完成的付给前端，让其点开就可以直接完成作业，如果全完成了，随便取出一条即可
				MidoHomeworkMainVO mode2Temp = null;

				if (mode2.size() != mode2Ok.size()) {
					mode2Temp = mode2NotOk.get(0);
					mode2Temp.setStatus("1");
				} else {
					mode2Temp = mode2Ok.get(0);
				}

				mode2Temp.setTargetGroupCount(mode2.size());
				mode2Temp.setOkGroupCount(mode2Ok.size());

				if (mode2.stream().anyMatch(x -> "1".equals(x.getDing()))) {
					mode2Temp.setDing("1");
				}
				resultList.add(mode2Temp);
			}

		}

		Collections.sort(resultList, new Comparator<MidoHomeworkMainVO>() {
			@Override
			public int compare(MidoHomeworkMainVO o1, MidoHomeworkMainVO o2) {
				if ("2".equals(o1.getStatus()) && "2".equals(o2.getStatus())) {
					return 0;
				} else if ("2".equals(o1.getStatus()) && !"2".equals(o2.getStatus())) {
					return 1;
				} else if (!"2".equals(o1.getStatus()) && "2".equals(o2.getStatus())) {
					return -1;
				} else {
					return 0;
				}
			}
		});

		// 筛选已完成的作业
		if ("1".equals(isAllOk)) {
			List<MidoHomeworkMainVO> allOkRes = resultList.stream()
					.filter(x -> x.getTargetGroupCount() <= x.getOkGroupCount())
					.collect(Collectors.toList());
			return new R(allOkRes);
		}

		return new R(resultList);
	}

	/**
	 * 教师获取学生作业列表 - 多师琴房
	 *
	 * @param startDate
	 * @param studentId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/28 13:26
	 */
	@ApiOperation("获取作业列表(分页)")
	@GetMapping("/getHomeworkV3")
	public R getHomeworkV3(String startDate, String studentId, Integer musicId, String isParentMode,
			String isAllOk, String classroomId, String teacherId) {

		//定义返回的结构体
		List<MidoHomeworkMainVO> finalList = new ArrayList<>();
		//定义教师集合
		List<String> teacherIds = new ArrayList<>();

		if (StringUtils.isNotBlank(teacherId)) {
			teacherIds.add(teacherId);
		} else if (StringUtils.isNotBlank(classroomId)) {
			//根据班级ID获取教师集合
			List<MyTeacherVO> teachers = memberService.getTeacherListByRoomIdFeign(classroomId);
			if (CollectionUtils.isEmpty(teachers)) {
				//如果没查到教师,则返回空作业列表
				return new R(finalList);
			} else {
				List<String> teacherIdsFeign = teachers.stream().map(x -> x.getTeacherId()).collect(Collectors.toList());
				teacherIds.addAll(teacherIdsFeign);
			}
		}

		//是否是学生调用
		boolean isStudent = ("-1".equals(studentId)) ? true : false;

		//学生筛选曲目作业
		if ("-1".equals(studentId)) {
			//member_id
			String memberId = SecurityUtils.getMember().getId();
			//根据member_id获取学生ID
			studentId = studentFeignService.getStudentId(memberId);
		}

		if (isStudent) {

			if (StringUtils.isNotBlank(isParentMode)) {
				if (StringUtils.equals("0", isParentMode)) {
					//学生 作业模式
					List<MidoHomeworkMainVO> tmpList = mainMapper
							.getHomeworkV3(studentId, startDate, musicId, isParentMode, teacherIds);
					if (CollectionUtils.isNotEmpty(tmpList)) {
						finalList.addAll(tmpList);
					}

				} else if (StringUtils.equals("1", isParentMode)) {

					//学生 家长模式 自己留作业
					List<MidoHomeworkMainVO> tmpList = mainMapper
							.getHomework(studentId, startDate, musicId, isParentMode,
									HomeWorkConstants.PARENT_MODE_TEACHER_ID);
					if (CollectionUtils.isNotEmpty(tmpList)) {
						finalList.addAll(tmpList);
					}
				}
			}

		} else {
			//老师 作业模式
			List<MidoHomeworkMainVO> tmpList = mainMapper.getHomeworkV3(studentId, startDate, musicId, isParentMode, teacherIds);

			if (CollectionUtils.isNotEmpty(tmpList)) {
				finalList.addAll(tmpList);
			}

		}

		finalList.stream().sorted((n1, n2) -> n2.getId().compareTo(n1.getId()))
				.collect(Collectors.toList());

		dealwithHomeworkList(finalList);

		//取出所有的 groupId
		List<Long> groupIdSet = finalList.stream()
				.sorted(Comparator.comparing(MidoHomeworkMainVO::getCreateTime))
				.map(MidoHomeworkMainVO::getGroupId).distinct().collect(Collectors.toList());

		List<MidoHomeworkMainVO> resultList = new ArrayList<>();

		//新增整合逻辑，将单条作业整合成一组，以各个模式区分
		for (Long groupId : groupIdSet) {

			//试听模式数据（理论上集合大小为 1 或 0 ）
			List<MidoHomeworkMainVO> mode0 = finalList.stream()
					.filter(n -> groupId.equals(n.getGroupId()) && "0".equals(n.getPlayingMode()))
					.collect(Collectors.toList());

			if (mode0 != null && mode0.size() != 0) {

				for (MidoHomeworkMainVO mode0Temp : mode0) {
					mode0Temp.setTargetGroupCount(mode0Temp.getTargetScore());
					mode0Temp.setOkGroupCount(mode0Temp.getOkCountOrScore());

					if (mode0.stream().anyMatch(x -> "1".equals(x.getDing()))) {
						mode0Temp.setDing("1");
					}
					resultList.add(mode0Temp);
				}

			}

			//识谱模式作业
			List<MidoHomeworkMainVO> mode1 = finalList.stream()
					.filter(n -> groupId.equals(n.getGroupId()) && "1".equals(n.getPlayingMode()))
					.collect(Collectors.toList());

			//识谱模式已完成作业
			List<MidoHomeworkMainVO> mode1Ok = finalList.stream()
					.filter(n -> groupId.equals(n.getGroupId()) && "1".equals(n.getPlayingMode())
							&& "2".equals(n.getStatus()))
					.collect(Collectors.toList());

			//识谱模式未完成作业
			List<MidoHomeworkMainVO> mode1NotOk = finalList.stream()
					.filter(n -> groupId.equals(n.getGroupId()) && "1".equals(n.getPlayingMode())
							&& "0".equals(n.getStatus()))
					.collect(Collectors.toList());

			if (mode1 != null && mode1.size() != 0) {

				MidoHomeworkMainVO mode1Temp = null;

				if (mode1.size() != mode1Ok.size()) {
					mode1Temp = mode1NotOk.get(0);
					mode1Temp.setStatus("1");
				} else {
					mode1Temp = mode1Ok.get(0);
				}

				mode1Temp.setTargetGroupCount(mode1.size());
				mode1Temp.setOkGroupCount(mode1Ok.size());

				if (mode1.stream().anyMatch(x -> "1".equals(x.getDing()))) {
					mode1Temp.setDing("1");
				}
				if (mode1.stream().anyMatch(x -> "1".equals(x.getIsHelp()))) {
					mode1Temp.setIsHelp("1");
				}

				resultList.add(mode1Temp);
			}

			//纠错模式作业
			List<MidoHomeworkMainVO> mode2 = finalList.stream()
					.filter(n -> groupId.equals(n.getGroupId()) && "2".equals(n.getPlayingMode()))
					.collect(Collectors.toList());

			//纠错模式已完成作业
			List<MidoHomeworkMainVO> mode2Ok = finalList.stream()
					.filter(n -> groupId.equals(n.getGroupId()) && "2".equals(n.getPlayingMode())
							&& "2".equals(n.getStatus()))
					.collect(Collectors.toList());

			//纠错模式未完成作业
			List<MidoHomeworkMainVO> mode2NotOk = finalList.stream()
					.filter(n -> groupId.equals(n.getGroupId()) && "2".equals(n.getPlayingMode())
							&& "0".equals(n.getStatus()))
					.collect(Collectors.toList());

			if (mode2 != null && mode2.size() != 0) {

				//挑选未完成的付给前端，让其点开就可以直接完成作业，如果全完成了，随便取出一条即可
				MidoHomeworkMainVO mode2Temp = null;

				if (mode2.size() != mode2Ok.size()) {
					mode2Temp = mode2NotOk.get(0);
					mode2Temp.setStatus("1");
				} else {
					mode2Temp = mode2Ok.get(0);
				}

				mode2Temp.setTargetGroupCount(mode2.size());
				mode2Temp.setOkGroupCount(mode2Ok.size());

				if (mode2.stream().anyMatch(x -> "1".equals(x.getDing()))) {
					mode2Temp.setDing("1");
				}
				if (mode2.stream().anyMatch(x -> "1".equals(x.getIsHelp()))) {
					mode2Temp.setIsHelp("1");
				}
				resultList.add(mode2Temp);
			}

		}

		Collections.sort(resultList, new Comparator<MidoHomeworkMainVO>() {
			@Override
			public int compare(MidoHomeworkMainVO o1, MidoHomeworkMainVO o2) {
				if ("2".equals(o1.getStatus()) && "2".equals(o2.getStatus())) {
					return 0;
				} else if ("2".equals(o1.getStatus()) && !"2".equals(o2.getStatus())) {
					return 1;
				} else if (!"2".equals(o1.getStatus()) && "2".equals(o2.getStatus())) {
					return -1;
				} else {
					return 0;
				}
			}
		});

		// 筛选已完成的作业
		if ("1".equals(isAllOk)) {
			List<MidoHomeworkMainVO> allOkRes = resultList.stream()
					.filter(x -> x.getTargetGroupCount() <= x.getOkGroupCount())
					.collect(Collectors.toList());
			return new R(allOkRes);
		}

		return new R(resultList);
	}

	/**
	 * 教师获取学生作业列表内的详情 - 更新提醒状态
	 *
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/28 13:26
	 */
	@ApiOperation("获取作业列表详情")
	@GetMapping("/getHomeworkV2Detail")
	public R getHomeworkV2Detail(String groupId, String playingMode, String studentId,
			String isParentMode, String startDate) {

		startDate = startDate.substring(0, 10);

		//学生筛选曲目作业
		if ("-1".equals(studentId)) {
			//member_id
			String memberId = SecurityUtils.getMember().getId();
			//根据member_id获取学生ID
			studentId = studentFeignService.getStudentId(memberId);
		}
		if ("1".equals(isParentMode)) {

			List<MidoHomeworkMainVO> homeworkV2Detail = mainMapper
					.getHomeworkV2Detail(Long.parseLong(groupId), playingMode,
							HomeWorkConstants.PARENT_MODE_TEACHER_ID, studentId, startDate);

			for (MidoHomeworkMainVO midoHomeworkMainVO : homeworkV2Detail) {
				midoHomeworkMainVO.setRecordingSrc(
						minioTemplate.getPrivateDownloadUrl(midoHomeworkMainVO.getRecordingSrc()));
			}

			return new R(homeworkV2Detail);
		}

		List<MidoHomeworkMainVO> homeworkV2Detail = mainMapper
				.getHomeworkV2Detail(Long.parseLong(groupId), playingMode,
						teacherFeignService.getCurTeacherIdByStu(studentId), studentId, startDate);

		List<MidoHomeworkMainVO> modeOk = null;

		if ("1".equals(playingMode)) {
			//识谱模式已完成作业
			modeOk = homeworkV2Detail.stream()
					.filter(n -> "1".equals(n.getPlayingMode()) && "2".equals(n.getStatus()))
					.collect(Collectors.toList());
		} else if ("2".equals(playingMode)) {
			//纠错模式已完成作业
			modeOk = homeworkV2Detail.stream()
					.filter(n -> "2".equals(n.getPlayingMode()) && "2".equals(n.getStatus()))
					.collect(Collectors.toList());
		}

		for (MidoHomeworkMainVO n : homeworkV2Detail) {

			if ("0".equals(n.getPlayingMode())) {
				n.setTargetGroupCount(n.getTargetScore());
				n.setOkGroupCount(n.getOkCountOrScore());
			} else {
				n.setTargetGroupCount(homeworkV2Detail.size());
				n.setOkGroupCount(modeOk.size());
			}

		}

		List<MidoHomeworkMainVO> homeworkV2DetailResult = homeworkV2Detail.stream()
				.sorted((n1, n2) -> Integer.parseInt(n2.getStatus()) - Integer
						.parseInt(n1.getStatus()))
				.collect(Collectors.toList());

		// 录音文件新增 token 参数
		for (MidoHomeworkMainVO midoHomeworkMainVO : homeworkV2DetailResult) {
			midoHomeworkMainVO.setRecordingSrc(
					minioTemplate.getPrivateDownloadUrl(midoHomeworkMainVO.getRecordingSrc()));
		}

		return new R(homeworkV2DetailResult);
	}

	/**
	 * 教师获取学生作业列表内的详情 - 更新提醒状态
	 *
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/28 13:26
	 */
	@ApiOperation("获取作业列表详情")
	@GetMapping("/getHomeworkV3Detail")
	public R getHomeworkV3Detail(String groupId, String playingMode, String studentId, String teacherId,
			String isParentMode, String startDate) {

		startDate = startDate.substring(0, 10);

		//学生筛选曲目作业
		if ("-1".equals(studentId)) {
			//member_id
			String memberId = SecurityUtils.getMember().getId();
			//根据member_id获取学生ID
			studentId = studentFeignService.getStudentId(memberId);
		}
		if ("1".equals(isParentMode)) {

			List<MidoHomeworkMainVO> homeworkV2Detail = mainMapper
					.getHomeworkV2Detail(Long.parseLong(groupId), playingMode,
							HomeWorkConstants.PARENT_MODE_TEACHER_ID, studentId, startDate);

//			for (MidoHomeworkMainVO midoHomeworkMainVO : homeworkV2Detail) {
//				midoHomeworkMainVO.setRecordingSrc(
//						minioTemplate.getPrivateDownloadUrl(midoHomeworkMainVO.getRecordingSrc()));
//			}

			return new R(homeworkV2Detail);
		}

		List<MidoHomeworkMainVO> homeworkV2Detail = mainMapper
				.getHomeworkV2Detail(Long.parseLong(groupId), playingMode, teacherId, studentId, startDate);

		List<MidoHomeworkMainVO> modeOk = null;

		if ("1".equals(playingMode)) {
			//识谱模式已完成作业
			modeOk = homeworkV2Detail.stream()
					.filter(n -> "1".equals(n.getPlayingMode()) && "2".equals(n.getStatus()))
					.collect(Collectors.toList());
		} else if ("2".equals(playingMode)) {
			//纠错模式已完成作业
			modeOk = homeworkV2Detail.stream()
					.filter(n -> "2".equals(n.getPlayingMode()) && "2".equals(n.getStatus()))
					.collect(Collectors.toList());
		}

		for (MidoHomeworkMainVO n : homeworkV2Detail) {

			if ("0".equals(n.getPlayingMode())) {
				n.setTargetGroupCount(n.getTargetScore());
				n.setOkGroupCount(n.getOkCountOrScore());
			} else {
				n.setTargetGroupCount(homeworkV2Detail.size());
				n.setOkGroupCount(modeOk.size());
			}

		}

		List<MidoHomeworkMainVO> homeworkV2DetailResult = homeworkV2Detail.stream()
				.sorted((n1, n2) -> Integer.parseInt(n2.getStatus()) - Integer
						.parseInt(n1.getStatus()))
				.collect(Collectors.toList());

		// 录音文件新增 token 参数
//		for (MidoHomeworkMainVO midoHomeworkMainVO : homeworkV2DetailResult) {
//			midoHomeworkMainVO.setRecordingSrc(
//					minioTemplate.getPrivateDownloadUrl(midoHomeworkMainVO.getRecordingSrc()));
//		}

		return new R(homeworkV2DetailResult);
	}

	/**
	 * 获取最近一个月的作业辅导情况
	 *
	 * @param startDate
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/7/3 17:39
	 */
	@ApiOperation("获取最近一个月的作业辅导情况")
	@GetMapping("getHomeworkHelpMonth")
	public R getHomeworkHelpMonth(String startDate, String studentId) {
		return mainService.getHomeworkHelpMonth(startDate, studentId,
				("-1".equals(studentId)) ? true : false);
	}

	/**
	 * 获取作业辅导列表
	 *
	 * @param startDate
	 * @param studentId
	 * @param musicId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/12/23 13:59
	 **/
	@GetMapping("getHomeworkHelp")
	public R getHomeworkHelp(String startDate, String studentId, Integer musicId) {

		startDate = startDate.substring(0, 10);

		//是否是学生调用
		boolean isStudent = ("-1".equals(studentId)) ? true : false;

		//学生筛选曲目作业
		if ("-1".equals(studentId)) {
			//member_id
			String memberId = SecurityUtils.getMember().getId();
			//根据member_id获取学生ID
			studentId = studentFeignService.getStudentId(memberId);
		}

		List<MidoHomeworkMainVO> finalList = new ArrayList<>();

		if (isStudent) {
			List<MidoHomeworkMainVO> tmpList = mainMapper.getHomework(studentId, startDate, musicId, "0", null);
			if (CollectionUtils.isNotEmpty(tmpList)) {
				finalList.addAll(tmpList);
			}
		} else {
			List<MidoHomeworkMainVO> tmpList = mainMapper.getHomework(
					studentId, startDate, musicId, "0",
					teacherFeignService.getCurTeacherIdByStu(studentId));

			if (CollectionUtils.isNotEmpty(tmpList)) {
				finalList.addAll(tmpList);
			}

		}

		// 辅导作业列表要求显示识谱纠错和已完成的作业
		finalList = finalList.stream()
				.filter(x -> "2".equals(x.getStatus()) && !"0".equals(x.getPlayingMode()) && "1"
						.equals(x.getIsHelp()))
				.sorted((n1, n2) -> Integer.parseInt(n1.getStatus()) - Integer
						.parseInt(n2.getStatus()))
				.collect(Collectors.toList());
		dealwithHomeworkList(finalList);
		return new R(finalList);
	}

	/**
	 * 获取辅导作业筛选列表
	 *
	 * @param startDate
	 * @param studentId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/7/8 9:35
	 */
	@GetMapping("getHomeworkHelpMusicList")
	@ApiOperation("获取作业筛选列表")
	public R getHomeworkHelpMusicList(String startDate, String studentId) {

		//是否是学生调用
		boolean isStudent = ("-1".equals(studentId)) ? true : false;

		//学生筛选曲目作业
		if ("-1".equals(studentId)) {
			//member_id
			String memberId = SecurityUtils.getMember().getId();
			//根据member_id获取学生ID
			studentId = studentFeignService.getStudentId(memberId);
		}

		//家长模式的作业
		List<MusicNameVO> resultList = new ArrayList<>();

		if (isStudent) {

			//选取现在所有的老师记录
			List<String> teacherIdList = teacherFeignService.getTeacherIdsByStudentId(studentId);
			//选取之前解绑的老师记录
			List<OrgRelationshipUnlinkLog> unlinkTeacherLogs = teacherFeignService
					.getUniqueTeacherUnlinkLog(studentId);

			if (unlinkTeacherLogs != null && unlinkTeacherLogs.size() != 0) {

				for (OrgRelationshipUnlinkLog log : unlinkTeacherLogs) {

					//学生还未绑定教师，也要显示之前老师留的作业
					if (teacherIdList.size() == 0) {
						resultList.addAll(mainMapper.getHomeworkHelpMusicList(studentId, startDate,
								log.getTeacherId()));
						continue;
					}

					for (String teacherId : teacherIdList) {
						if (!teacherId.equals(log.getTeacherId())) {
							resultList.addAll(mainMapper
									.getHomeworkHelpMusicList(studentId, startDate,
											log.getTeacherId()));
						}
					}
				}
			}

			if (teacherIdList != null && teacherIdList.size() != 0) {
				for (int i = 0; i < teacherIdList.size(); i++) {
					List<MusicNameVO> tempList = mainMapper
							.getHomeworkHelpMusicList(studentId, startDate, teacherIdList.get(i));
					resultList.addAll(tempList);
				}
			}
			resultList.stream().sorted((n1, n2) -> n2.getMusicId().compareTo(n1.getMusicId()))
					.collect(Collectors.toList());
		} else {
			resultList.addAll(mainService.getHomeworkMusicList(studentId, startDate,
					teacherFeignService.getCurTeacherIdByStu(studentId)));
		}
		return new R(resultList);
	}

	@GetMapping("scanFinishedAndCorrectStatus")
	@ApiOperation("扫描完成作业并纠正状态")
	public R scanFinishedAndCorrectStatus() {
		List<MidoHomeworkComplate> complateList =
				complateService.getBaseMapper()
						.selectList(new QueryWrapper<MidoHomeworkComplate>());

		log.info("一共查询到" + complateList.size() + "条完成记录");

		for (MidoHomeworkComplate complate : complateList) {
			MidoHomeworkMain main = mainMapper.selectOne(
					new QueryWrapper<MidoHomeworkMain>().eq("id", complate.getHomeworkId()));

			if (main == null) {
				log.info("从完成表未找到对应作业记录，complateId: " + complate.getId() + ", homeworkId: "
						+ complate.getHomeworkId());
				continue;
			}

			if ("0".equals(main.getPlayingMode())) {
				if (complate.getTotalScore().equals(main.getTargetScore())) {
					main.setStatus("2");
					mainMapper.updateById(main);
					log.info("纠正一条状态记录，[试听模式][已完成], homeworkId: " + main.getId());
				} else {
					main.setStatus("1");
					mainMapper.updateById(main);
					log.info("纠正一条状态记录，[试听模式][进行中], homeworkId: " + main.getId());
				}
			} else {
				if (!"2".equals(main.getStatus())) {
					main.setStatus("2");
					mainMapper.updateById(main);
					log.info("纠正一条状态记录，[纠错/识谱模式][已完成], homeworkId: " + main.getId());
				}
			}
		}

		return new R(CommonConstants.SUCCESS, "处理成功", true);
	}

	@PostMapping("/activeDetail")
	public R<AtvActiveDetailDataVO> activeDetail(@RequestBody AtvActiveDetailReqVO vo)
			throws Exception {
		/* 页面作业 只能完成作业相关 每日弹琴时间跟实际弹琴时间为准

		 */
		String mainActiveId = vo.getId();

		//日期范围遍历
		LocalDate beginDate = LocalDateTime
				.ofInstant(vo.getBeginDatetime().toInstant(), ZoneId.systemDefault()).toLocalDate();
		LocalDate endDate = LocalDateTime
				.ofInstant(vo.getEndDatetime().toInstant(), ZoneId.systemDefault()).toLocalDate();
		//任务天数
		long total = 0;
		if (endDate.equals(LocalDate.now()) || LocalDate.now().isAfter(endDate)) {
			total = ChronoUnit.DAYS.between(beginDate, endDate) + 1L;
		} else {
			total = ChronoUnit.DAYS.between(beginDate, LocalDate.now()) + 1L;
		}
		if (total <= 0) {
			total = 0;
		}

		long days = ChronoUnit.DAYS.between(beginDate, endDate);
		ArrayList<String> dateList = new ArrayList<>();

		Stream.iterate(beginDate, day -> {
			return day.plusDays(1);
		}).limit(days + 1).forEach(item -> {
			dateList.add(item.toString());
		});
		//获取作业详情
//		List<AtvActiveDetailItemVO> items = atvMainActiveService.studentActiveDatail(vo);
		List<AtvActiveDetailItemVO> itemsComplate = mainService.studentActiveDatailByComplate(vo);
		List<AtvActiveDetailItemVO> itemsHomework = mainService.studentActiveDatailByHomework(vo);

		AtvActiveDetailDataVO result = new AtvActiveDetailDataVO();
		result.setMemberId(vo.getMemberId());
		List<AtvActiveDetailItemVO> atvActiveDetailItemList = new ArrayList<>();
		//作业
		if (CollectionUtils.isEmpty(itemsHomework)) {
			for (int i = 0; i < dateList.size(); i++) {
				AtvActiveDetailItemVO defaultItem = new AtvActiveDetailItemVO();
				defaultItem.setIndex(1 + i);
				defaultItem.setActionDate(dateList.get(i));
				atvActiveDetailItemList.add(defaultItem);
			}
		} else {
			//是否全完成
			List<AtvActiveDetailItemVO> collect = itemsHomework.stream()
					.filter(item -> item.getDone() == 0).collect(Collectors.toList());
			if (CollectionUtils.isEmpty(collect)) {
				for (int i = 0; i < dateList.size(); i++) {
					AtvActiveDetailItemVO defaultItem = new AtvActiveDetailItemVO();
					defaultItem.setIndex(1 + i);
					defaultItem.setActionDate(dateList.get(i));
					atvActiveDetailItemList.add(defaultItem);
				}
			} else {
				//计算
				Map<String, AtvActiveDetailItemVO> homeworkMap = collect.stream().collect(Collectors
						.toMap(AtvActiveDetailItemVO::getActionDate, item -> item, (k1, k2) -> k1));

				for (int i = 0; i < dateList.size(); i++) {
					AtvActiveDetailItemVO detailItem = homeworkMap.get(dateList.get(i));
					if (Objects.isNull(detailItem)) {
						AtvActiveDetailItemVO defaultItem = new AtvActiveDetailItemVO();
						defaultItem.setIndex(1 + i);
						defaultItem.setActionDate(dateList.get(i));
						atvActiveDetailItemList.add(defaultItem);
					} else {
						detailItem.setIndex(1 + i);
						detailItem.setActionDate(dateList.get(i));
						detailItem.setActionFalg("1");
						//统计
						result.setPractiveDayCount(result.getPractiveDayCount() + 1);//天数
						atvActiveDetailItemList.add(detailItem);
					}
				}
			}

		}

		//弹琴处理

		//如果有弹琴数据
		if (CollectionUtils.isNotEmpty(itemsComplate)) {
			Map<String, AtvActiveDetailItemVO> complateMap = itemsComplate.stream().collect(
					Collectors.toMap(AtvActiveDetailItemVO::getActionDate, item -> item,
							(k1, k2) -> k1));
			for (AtvActiveDetailItemVO item : atvActiveDetailItemList) {
				AtvActiveDetailItemVO complate = complateMap.get(item.getActionDate());
				if (Objects.isNull(complate)) {
					item.setPractiveTotal(0L);
				} else {
					item.setPractiveTotal(
							Optional.<Long>ofNullable(complate.getPractiveTotal()).orElse(0L));
				}
				result.setPractiveTotal(result.getPractiveTotal() + item.getPractiveTotal());//练琴时长
			}
			//今日弹琴
			LocalDate nowDate = LocalDate.now();
			AtvActiveDetailItemVO nowItemVO = complateMap.get(nowDate.toString());
			if (Objects.nonNull(nowItemVO)) {
				result.setPractiveToday(nowItemVO.getPractiveTotal());
			}
		}
		result.setAtvActiveDetailItemList(atvActiveDetailItemList);

		//汇总
		if (total == 0L) {
			BigDecimal totalBD = new BigDecimal(result.getPractiveTotal());
			result.setPractiveAvg(totalBD);
			result.setPractiveAvgStr(totalBD.stripTrailingZeros().toPlainString());
			result.setPractiveLackDayCount(0L);
		} else {
			BigDecimal countBD = new BigDecimal(total);
			BigDecimal totalBD = new BigDecimal(result.getPractiveTotal());
			BigDecimal avgBD = totalBD.divide(countBD, 0, RoundingMode.HALF_UP);
			result.setPractiveAvg(avgBD);
			result.setPractiveAvgStr(avgBD.stripTrailingZeros().toPlainString());
			result.setPractiveLackDayCount(total - result.getPractiveDayCount());
		}

		return new R(result);
	}

	@GetMapping("updHomeworkVideo")
	public R updHomeworkVideo(String homeworkId, String videoUrl) {
		MidoHomeworkMain byId = mainService.getById(homeworkId);
		byId.setVideoUrl(videoUrl);
		return new R(mainService.updateById(byId));
	}

	@PostMapping("atvSchedule")
	@ApiOperation(value = "小程序挑战赛活动进度接口（feign 专用）", notes = "由于与作业相关连，所以放在作业模块下")
	public List<AtvScheduleVO> atvSchedule(@RequestBody AtvScheduleReqVO vo) {
		return mainService.atvSchedule(vo);
	}

	@PostMapping("atvScheduleDetail")
	@ApiOperation(value = "APP挑战赛活动进度接口（feign 专用）", notes = "由于与作业相关连，所以放在作业模块下")
	public List<AtvScheduleVO> atvScheduleDetail(@RequestBody AtvScheduleReqVO vo) {
		return mainService.atvScheduleDetail(vo);
	}

	@GetMapping("getHomeWorkStatusByStu")
	public List<String> getHomeWorkStatusByStu(String startDate, String studentId) {
		return mainMapper.getHomeWorkStatusByStuStr(startDate, studentId);
	}

}
